import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class TcpEchoServer {
    private ServerSocket serverSocket=null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start()throws IOException{
        System.out.println("服务器启动！");

while (true){
    Socket clientSocket=serverSocket.accept();
    Thread t=new Thread(()->{
        processConnection(clientSocket);
    });
    t.start();
}
      /*  ExecutorService service= Executors.newCachedThreadPool();
       while (true){
           Socket clientSocket=serverSocket.accept();//通过accept方法建立连接
           service.submit(new Runnable() {
               @Override
               public void run() {
processConnection(clientSocket);
               }
           });
       }*/
    }
    //通过这个方法来处理当前的连接
    private void processConnection(Socket clientSocket) {

        System.out.printf("%s:%d 客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
       //接下来进行数据交互
       try(InputStream inputStream= clientSocket.getInputStream();
           OutputStream outputStream= clientSocket.getOutputStream()) {
         //使用try方式，避免了后面使用了数据流忘记关闭
           while (true){
               Scanner scanner=new Scanner(inputStream);
               if (!scanner.hasNext()){
                   System.out.printf("%s:%d 客户端下线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
               }
               //1读取请求并解析，以next作为请求的方式，遇到空白符则返回
               String request=scanner.next();
               String response=process(request);//2做出响应
               //3,写回响应，通过printwriter对数据流进行包装
               PrintWriter printWriter=new PrintWriter(outputStream);
               printWriter.println(response);//此处的println是写入到clientServer,不是控制台
               System.out.printf("[%s:%d],req=%s,resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
           }
       } catch (IOException e) {
           throw new RuntimeException(e);
       }finally {//在这个地方进行cleentsocket的关闭，processconnect是在处理一个链接，连接处理完毕就要关闭clientsocket
           try {
               clientSocket.close();

           } catch (IOException e) {
               throw new RuntimeException(e);
           }
       }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }
}
